import { useMessage } from "/@/hooks/web/useMessage";
const { createMessage: msg } = useMessage();
var usb = ""
function SendCommand (mData) {
	// Get Json Object ( Printer Config )
	var JsonObject = { "Interface": "USB", "USB": "", "COM": "", "BaudRate": "", "LPT": "", "IP": "", "Port": "", "Data": "RQ==" }

	// Encode data
	mData = $.base64.encode(mData);

	// Add Data to Json Object
	JsonObject['Data'] = mData;

	// Send To Printer
	SendToPrinter("Send", JsonObject);
}

function PrinterCtrl_GetJson () {
	return {
		usb: usb
	}
}
class Print {
	constructor() {
		this.status = false
		this.nowPrint = ''
		this.timer = null
	}
	init () {
		return new Promise((resolve, reject) => {
			msg.loading("正在连接打印机...")
			let page = 0
			let func = () => {
				page++
				if (page > 3) {
					this.stop()
					return
				}
				var RetData = QueryUsbList();
				console.log(RetData, 'RetData')
				if (!RetData.length) {
					this.status = false
					this.nowPrint = ''
					// 未检测到打印机重新检测
					msg.destroy()
					msg.loading("连接打印机失败，待重连")
					this.timer = setTimeout(() => {
						func()
					}, 2000)
				} else {
					this.nowPrint = RetData[0]
					this.status = true
					usb = RetData[0]
					msg.success("连接成功")
					clearTimeout(this.timer)
					resolve(this)
				}
			}
			func()
		})
	}
	sendPrint (list) {
		list.forEach(item => {
			// Set Label Size
			SendCommand("^Q" + 54 + ",0,0\n^W" + 40);
			// Print Job Start
			SendCommand("^L");
			var mData = item;
			mData = $.base64.encode(mData);
			// JsonObject['Data'] = mData;

			var JsonObject = { "Interface": "USB", "USB": "", "COM": "", "BaudRate": "", "LPT": "", "IP": "", "Port": "", "BarcodeType": "A", "PosX": "10", "PosY": "10", "Narrow": "2", "Wide": "8", "Height": "120", "Rotation": "0", "Readable": "1", "Data": mData }

			console.log(JSON.stringify(JsonObject), 'JsonObject')

			SendToPrinter("PrintBarcode", JsonObject);

			// Print Job End
			SendCommand("E");

		})

	}
	stop () {
		clearTimeout(this.timer)
	}
}
export default new Print()